<template>
  <!-- <div class="Event"> -->
  <!-- ----------------------------------------------
                        事件管理
    ----------------------------------------------- -->

  <div class="event-maneger" type="primary">
    <el-dropdown>
      <span>事件管理</span>
      <img src="../assets/nav-img/shijian.svg" alt="" type="primary" />
      <i class="el-icon-arrow-down el-icon--right"></i>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click.native="activedraw">事件查询</el-dropdown-item>
        <el-dropdown-item @click.native="activeAdd()"
          >事件添加</el-dropdown-item
        >
        <el-dropdown-item @click.native="activeUpdate()"
          >事件更新</el-dropdown-item
        >
      </el-dropdown-menu>
    </el-dropdown>

    <!-- 外层弹出框 -->
    <el-dialog
      v-dialogDrag
      title="查询结果"
      :visible.sync="dialogTableVisible"
      @close="closeDialog"
      :modal="false"
      :close-on-click-modal="false"
      center
    >
      <el-button type="primary" plain @click="innerVisible = true"
        >统计图</el-button
      >
      <el-button type="success" plain @click="showHeatMap">热力图</el-button>
      <!-- <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item title="查询数据表格" name="1"> -->
      <!-- 查询表格 -->
      <el-table
        :data="
          gridData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        height="500"
        style="width: 100%"
        border
      >
        <el-table-column property="fid" label="编号"></el-table-column>
        <el-table-column property="type" label="事件类型"> </el-table-column>
        <el-table-column property="level" label="事故等级"></el-table-column>
        <el-table-column property="time" label="事故发生时间"></el-table-column>
        <el-table-column property="place" label="发生地点"></el-table-column>
        <el-table-column
          property="license_number"
          label="车牌号"
        ></el-table-column>
        <el-table-column property="username" label="驾驶员"></el-table-column>
        <el-table-column property="state" label="处理状态"></el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <span class="demonstration">调整每页显示条数</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="gridData.length"
        >
        </el-pagination>
      </div>
    </el-dialog>
    <!-- 统计图弹出框 -->
    <el-dialog
      v-dialogDrag
      title="查询结果"
      :visible.sync="innerVisible"
      append-to-body
      @open="open"
      width="640px"
    >
      <el-button
        type="success"
        plain
        @click="(echarts_type = true), (echarts_months = false)"
        >按类型统计</el-button
      >
      <el-button
        type="primary"
        plain
        @click="(echarts_months = true), (echarts_type = false)"
        >按月份统计</el-button
      >
      <div
        id="main"
        style="width: 600px; height: 600px"
        v-show="echarts_type"
      ></div>
      <div
        id="main_months"
        style="width: 600px; height: 600px"
        v-show="echarts_months"
      ></div>
    </el-dialog>
  </div>
  <!-- </div> -->
</template>

<script>
var map;
var heatmapSource;
var features;
var heatmapLayer;
var highLightLayer;
import Bus from '../../utils/bus';
import { createDraw } from '../../utils/Draw';
import addEvent from './addEvent.vue';
import * as echarts from 'echarts';
export default {
  components: {
    addEvent,
  },
  data() {
    return {
      username: '',
      usertype: '',
      activeNames: ['1'],
      dialogTableVisible: false,
      innerVisible: false,
      gridData: [], //拉框查询数据
      echartsData_type: [], //按类型分类数据
      echartsData_month: [], //按月份分类数据
      echarts_months: false,
      echarts_type: true,
      currentPage: 1,
      pageSize: 5,
    };
  },
  mounted() {},
  methods: {
    initCharts_type() {
      // 初始化echarts实例
      var myChart = echarts.init(document.getElementById('main'));
      // 绘制图表
      myChart.setOption({
        title: {
          text: '交通事件' + this.gridData.length + '起',
          padding: [20, 0, 0, 20],
          textStyle: {
            fontweight: 'normal',
            color: '#acf',
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
          orient: 'vertical',
          bottom: '50px',
          right: '20px',
          data: this.echartsData_type,
        },
        backgroundColor: '#fff',
        toolbox: {
          show: true,
          feature: {
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            // roseType: "angle",
            data: this.echartsData_type,
            label: {
              //饼图文字的显示
              show: true, //默认  显示文字
              formatter: function (arg) {
                return arg.name + ' 发生 ' + arg.value + '起';
              },
            },
            // selectedMode: 'single' //选中的效果，能够将选中的区域偏离圆点一小段距离
            selectedMode: 'single',
            selectedOffset: 30,
          },
        ],
      });
    },
    initCharts_months() {
      // 初始化echarts实例
      var myChart = echarts.init(document.getElementById('main_months'));
      // 绘制图表
      myChart.setOption({
        title: {
          text: '交通事件' + this.gridData.length + '起',
          padding: [20, 0, 0, 20],
          textStyle: {
            fontweight: 'normal',
            color: '#acf',
          },
        },
        tooltip: {},
        legend: {
          data: ['销量'],
        },
        xAxis: {
          data: [
            '1月',
            '2月',
            '3月',
            '4月',
            '5月',
            '6月',
            '7月',
            '8月',
            '9月',
            '10月',
            '11月',
            '12月',
          ],
        },
        yAxis: {},
        series: [
          {
            name: '交通事件',
            type: 'bar',
            data: this.echartsData_month,
            markLine: {
              data: [{ type: 'average', name: '平均值' }],
            },
          },
        ],
      });
    },
    activedraw() {
      var that = this;
      map = this.$store.state.map;
      if ((that.innerVisible = false)) {
        map.removeLayer(highLightLayer);
      }
      /* 1、激活画布,获取坐标 */
      var source = new ol.source.Vector({
        wrapX: false,
      });
      var layer = new ol.layer.Vector({
        source,
      });
      map.addLayer(layer);
      var draw = createDraw({
        type: 'Rectangle',
        source,
        callback: handleDraw,
      });
      map.addInteraction(draw);
      /* 获取坐标 */
      function handleDraw(e) {
        source.clear();
        var geometry = e.feature.getGeometry();
        //1、初始化查询结构对象，设置查询结构包含几何信息
        var queryStruct = new Zondy.Service.QueryFeatureStruct();
        //是否包含几何图形信息
        queryStruct.IncludeGeometry = true;
        //是否包含图形显示参数
        queryStruct.IncludeWebGraphic = true;
        //2、创建一个用于查询的区
        var geomObj = new Zondy.Object.Polygon();
        geomObj.setByOL(geometry);
        //3、指定查询规则
        var rule = new Zondy.Service.QueryFeatureRule({
          //是否将要素的可见性计算在内
          EnableDisplayCondition: false,
          //是否完全包含
          MustInside: false,
          //是否仅比较要素的外包矩形
          CompareRectOnly: false,
          //是否相交
          Intersect: true,
        });
        //4、实例化查询参数对象
        var queryParam = new Zondy.Service.QueryParameter({
          geometry: geomObj,
          resultFormat: 'json',
          struct: queryStruct,
          rule: rule,
          recordNumber: 50,
        });
        //5、实例化地图文档查询服务对象
        var queryService = new Zondy.Service.QueryDocFeature(
          queryParam,
          'guanggu',
          3,
          {
            ip: 'localhost',
            port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089
          }
        );
        //执行查询操作，querySuccess为查询回调函数
        queryService.query(querySuccess);
      }
      /* 设置高亮图层 */
      var highLightSource = new ol.source.Vector({ wrapX: false });
      highLightLayer = new ol.layer.Vector({
        source: highLightSource,
      });
      highLightLayer.setStyle(
        new ol.style.Style({
          /**{olx.style.IconOptions}类型*/
          image: new ol.style.Icon({
            anchor: [0.5, 60],
            anchorOrigin: 'top-right',
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            offsetOrigin: 'top-right',
            // offset:[0,10],
            //图标缩放比例
            scale: 0.5,
            //透明度
            opacity: 0.75,
            //图标的url
            src: '../../img/blueIcon.png',
          }),
        })
      );
      map.addLayer(highLightLayer);
      function querySuccess(e) {
        /* 将mapgis的要素转化ol要素 */
        //初始化Zondy.Format.PolygonJSON类
        var format = new Zondy.Format.PolygonJSON();
        //将MapGIS要素JSON反序列化为ol.Feature类型数组
        features = format.read(e);
        // console.log(features)
        if (features) {
          highLightSource.addFeatures(features);
        }
        var arr = e.SFEleArray;
        // console.log(e);
        // console.log(arr);
        arr.forEach((item) => {
          var arrdata = {};
          var tds = item.AttValue;
          arrdata.fid = tds[0];
          arrdata.type = tds[1];
          if (tds[2] == '1') {
            arrdata.level = '轻微事故';
          } else if (tds[2] == '2') {
            arrdata.level = '一般事故';
          } else if (tds[2] == '3') {
            arrdata.level = '重大事故';
          } else {
            arrdata.level = '特大事故';
          }
          // arrdata.level = tds[2];

          arrdata.time = tds[3];
          arrdata.place = tds[4];
          arrdata.license_number = tds[5];
          arrdata.username = tds[6];
          if (tds[7] == 0) {
            arrdata.state = '待处理';
          } else if (tds[7] == 1) {
            arrdata.state = '处理中';
          } else {
            arrdata.state = '已归档';
          }
          that.gridData.push(arrdata);
        });
        // console.log(that.gridData);
        // that.echartsData_type = [];
        // 转换echarts数组
        that.echartsData_type = that.toEchartsArr(that.gridData);
        that.echartsData_month = that.getmonth(that.gridData);
        that.dialogTableVisible = true;
        // map.removeLayer(highLightLayer);
        map.removeInteraction(draw);
        source.clear();
        for (var i = 0; i < features.length; i++) {
          features[i].set(
            'weight',
            parseFloat(e.SFEleArray[i].AttValue[3]) * 0.2
          );
        }
        if (!heatmapSource) {
          heatmapSource = new ol.source.Vector({
            wrapX: false,
          });
          heatmapLayer = new ol.layer.Heatmap({
            source: heatmapSource,
            radius: 10,
            blur: 10,
          });
          map.addLayer(heatmapLayer);
        }
        // heatmapSource.addFeatures(features);
      }
    },
    closeDialog() {
      this.innerVisible = false;
      this.gridData = [];
      map.removeLayer(highLightLayer);
      // heatmapSource.removeFeatures(features);
      heatmapSource.clear();
    },
    open() {
      this.$nextTick(() => {
        this.initCharts_months();
        this.initCharts_type();
      });
    },
    toEchartsArr(gridData) {
      var newarr = [];
      gridData.forEach((item) => {
        newarr.push(item.type);
      });
      var echartsData_type = [];
      var newarr2 = [];
      var objdata = {};
      for (var i = 0; i < newarr.length; i++) {
        var value = newarr[i];
        if (newarr2.indexOf(newarr[i]) === -1) {
          newarr2.push(newarr[i]);
        }
        if (!objdata[value]) {
          objdata[value] = 1;
        } else {
          objdata[value]++;
        }
      }
      for (let key in objdata) {
        echartsData_type.push({
          value: objdata[key],
          name: key,
        });
      }
      return echartsData_type;
    },
    // 转换月份echarts表函数
    getmonth(gridData) {
      var arr = [];
      var arr1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      gridData.forEach((item) => {
        arr.push(item.time.split('.')[1]);
      });
      arr.map(Number);
      for (var i = 0; i < arr.length; i++) {
        arr1[arr[i] - 1] = arr1[arr[i] - 1] + 1;
      }
      // console.log(arr);
      return arr1;
    },
    handleChange(val) {},
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    showHeatMap() {
      map.removeLayer(highLightLayer);
      heatmapSource.addFeatures(features);
      console.log(123);
    },
    // 事件添加
    activeAdd() {
      Bus.$emit('Add');
    },
    activeUpdate() {
      Bus.$emit('update');
    },
  },
};
</script>
<style scoped>
/* .Event {
  position: absolute;
  display: flex;
  top: 15px;
  right: 3px;
  width: 400px;
  height: 45px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 5px 5px 4px rgba(0, 0, 0, 0.6);
} */

/* -----------------------
        事件管理
------------------------ */
.event-maneger {
  position: absolute;
  top: 5px;
  left: 200px;
  width: 110px;
  height: 35px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.6);
}
.event-maneger:hover {
  background-color: #dbdbdb;
  color: white;
}
.event-maneger img {
  margin-top: 3px;
  margin-left: 6px;
}
.event-maneger span {
  position: relative;
  top: -10px;
  left: 6px;
  font-weight: 700;
  color: #7c8196;
}
.event-maneger span:hover {
  color: white;
}
.el-icon--right {
  position: relative;
  top: -8px;
  left: -4px;
}
.demonstration {
  top: 2px !important;
}
</style>
